Skip to content


tag  jupyter  tips  ai  deep learning  beginner  regression  reinforcement learning  q learning  gym  gymnasium  ardupilot  None  ros2  dds  micro ros  xrce  lua  sitl  scripts  plugin  gazebo  garden  SITL  debug  rangefinder  pymavlink  mavros  distance sensor  system_time  timesync  ardurover  cheat sheet  mission planner  cmake  gtest  ctest  101  cpp  c++  format  fmt  multithreading  spdlog  cyclonedds  eprosima  fastdds  aptly  apt  repository  repo  local  mirror  encryption  pgp  docker  arm  container  state  networking  network  nvidia  python  app  devcontainer  gui  tutorial  volume  mount  compose  multi-stage  stage  docker compose  git  bundle  submodules  github  hooks  pre-commit  lxd  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  mkdocs  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  pipe  compositor  gi  kml  geo  gis  spatial  gdal  ogr  raster  vector  snippets  cheat Sheet  asyncio  event  future  thread  task  can  canbus  click  cli  cupy  numpy  gpu  dataclass  slots  dev container  deb  debian  package  setup  stdeb  project  hydra  yaml  configuration  matplotlib  3d  subplot  open3d  point cloud  template  black  isort  templates  cookiecutter  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  from a-z  fixture  scope  logging  pytest.ini  mock  parameterize  enum  flag  iterator  generator  yml  logging config  tuple  namedtuple  typing  annotation  generic  literal  protocol  self  typed dict  typevar  pyzmq  zmq  opencv  msgpack  slam  cartographer  slam_toolbox  action  namespace  remap  control2  demo  diff-drive  ignition  ros2_control  effort  velocity  gdb  qos  plugins  msg  node  zero-copy  shm  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  settings  behavior  py_trees  bt  behavior_trees  blackboard  plot  visualization  debugging  diagnostic  DiagnosticTask  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  bag  rosbag  rosbags  tools  ros  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  model  cook  camera  sensors  gps  imu  ray  gazebo_ros_ray_sensor  lidar  ultrsonic  range  ultrasonic  gazebo classic  wrench  gz  sdf  world  vscode tips  gazebogz-sim-joint-position-controller-system  bridge  simulation  ros_gz_bridge  ign  xacro  diff_drive  odom  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  nav2  turtlebot  test  rclpy  goal abort  cancel goal  action client  action server  custom messages  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  local_setup  rosdep  package manager  project settings  vcstool  urdf  robot_state_publisher  urdf_to_graphiz  joint  link  zenoh  tags  hands on  webinar  cross-compiler  esp32  nano  jetson  i2c  adafruit  arduino  sensor  mb1202  uart  serial  tfmini  rpi  raspberry pi  arducam  teensy  microros  config  material  workshope  texture  joints  tmuxp  loop device  rootfs  embedded  zah  linux  rm  ubuntu  sudo  sudoers  nopasswd  visudo  udev  key  gpg  sign  commands  update-alternative  dpkg  ip  ss  netstat  snap  deploy  ssh  systemd  socat  udp  tc  mtu  select  robotics  path planning  trajectory  speed  pcl  kalman_filter  kalman  filter  control  code  extensions  remote  json  schema  yocto  poky  qemu  projects  courses to follow  matrix  graphics  rotation  2d  course  vision  drone  quad  uav  design  vrx  buoyancy 

Asyncio achieves concurrency through the use of coroutines. Coroutines are functions that can be paused and resumed at specific points during their execution. This allows multiple coroutines to run concurrently within a single thread.

When programming, asynchronous means that the action is requested/ schedule, although not performed at the time of the request. It is performed later.

  • coroutine is a function that can be suspended and resumed.

  • Future: A handle on an asynchronous function call allowing the status of the call to be checked and results to be retrieved.

  • Asynchronous Task: Used to refer to the aggregate of an asynchronous function call and resulting future

coroutine#

A coroutine is a regular function with the ability to pause and resume its execution

to mark function as coroutine we add the async keyword before def statement. To pause coroutine execution we use the await keyword.

async#

async mark function as coroutine coroutine execute on event loop there other asyncio method to register/schedule the coroutine on event loop

coroutine
async def hello() -> int:
    pass

co = hello()
print(co)
<coroutine object hello at 0x7f5058f6b530>
sys:1: RuntimeWarning: coroutine 'hello' was never awaited

await#

The await keyword pauses the execution of a coroutine

result = await my_coroutine()

The await keyword causes the my_coroutine() to execute, waits for the code to be completed, and returns a result.


asyncio app#

import asyncio
import logging

logging.basicConfig(format="[%(levelname)s] %(asctime)s %(message)s", level=logging.DEBUG)
log = logging.getLogger(__name__)

async def main():
    log.info("Starting coroutine")
    await asyncio.sleep(2)
    log.info("Coroutine finished")

asyncio.run(main())

The asyncio.run() function used to run a coroutine in an event loop. This function: - creates an event loop, - runs the coroutine in the event loop, - closes the event loop when the coroutine is complete.


Reference#